#!/bin/bash

OUTPUT="script_linux64"
ZIP_FILE="$OUTPUT.zip"
RELEASE_DIR="../release"
RESOURCE_DIR="resource"

echo "Building Linux binary for x86_64: $OUTPUT"

# 创建临时目录用于打包
TMP_DIR="build_tmp"
rm -rf "$TMP_DIR"
mkdir -p "$TMP_DIR"

# 创建 release 目录
if [ ! -d "$RELEASE_DIR" ]; then
  mkdir -p $RELEASE_DIR
fi

# 设置为 Linux x86_64 构建环境
if ! CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o "$TMP_DIR/$OUTPUT"; then
    echo "Build failed" >&2
    exit 1
fi

echo "Build succeeded: $TMP_DIR/$OUTPUT"

# 复制 resource 目录到临时目录
if [ -d "$RESOURCE_DIR" ]; then
    cp -r "$RESOURCE_DIR" "$TMP_DIR/"
    echo "Copied resource directory into package."
else
    echo "Resource directory not found, skipping." >&2
fi

# 打包整个目录
cd "$TMP_DIR" || exit 1
# shellcheck disable=SC2035
if ! zip -q -r "$ZIP_FILE" *; then
    echo "Failed to create ZIP file." >&2
    exit 1
fi

echo "Created ZIP file: $ZIP_FILE"

# 移动 ZIP 文件到 release 目录
cd ..
if ! mv -f "$TMP_DIR/$ZIP_FILE" "$RELEASE_DIR/"; then
    echo "Failed to move ZIP file." >&2
    exit 1
fi

echo "Moved zip to $RELEASE_DIR/$ZIP_FILE"

# 清理临时目录
rm -rf "$TMP_DIR"

echo "Build and packaging completed successfully."
